<template>
  <div style="display: flex; justify-content: center; padding-top: 80px">
    <el-card class="box-card">
      <div slot="header" class="clearfix" style="text-align: left">
        <span>修改密码</span>
      </div>
      <div class="text item">
        <el-form ref="formData" :model="formData" label-width="100px">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="formData.oldPassword"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="formData.newPassword"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input v-model="formData.confirmPassword"></el-input>
          </el-form-item>
          <el-form-item style="float: left; margin-left: 20px">
            <el-button type="primary" @click="submitEdit">确认修改</el-button>
            <el-button
              @click="resetForm('formData')"
              style="margin-left: 40px; width: 100px"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import "@/assets/PublicLess.less"
export default {
  data () {
    return {
      formData: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      userInfo: ''
    }
  },
  methods: {
    submitEdit () {
      this.userInfo = JSON.parse(localStorage.getItem("user"))
      const data = {
        oldPassword: this.formData.oldPassword,
        newPassword: this.formData.newPassword,
        uid: this.userInfo.uid
      }
      if (this.formData.oldPassword === '') {
        this.$message.error('原密码不能为空!')
      } else if(this.formData.newPassword === '') {
        this.$message.error('新密码不能为空!')
      } else if(this.formData.confirmPassword === ''){
        this.$message.error('确认新密码不能为空!')
      } else if(this.formData.oldPassword !== this.userInfo.password) {
        this.$message.error('原密码错误!')
      } else if(this.formData.newPassword !== this.formData.confirmPassword) {
        this.$message.error('两次输入的密码不一致!')
      } else {
        this.$axios.post('/api/users/editPassword', data).then(res => {
          if (res.data.code === 1) {
            this.$message.success(res.data.msg)
            this.formData.oldPassword = ''
            this.formData.newPassword = ''
            this.formData.confirmPassword = ''
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 500px;
  border-radius: 10px;
  background-color: #fffcfc;
}
</style>